package com.wang.java.basic.framework.queue;

import com.wang.common.domain.ComparableUser;
import com.wang.common.domain.User;

import java.util.PriorityQueue;

/**
 * 优先级队列，基于java.lang.Comparable接口实现对数据的排序
 * 数据结构：基于数组实现的小顶堆
 * 线程安全：否
 * 队列长度：无界，支持扩容
 * 阻塞性：非阻塞
 */
public class PriorityQueueTest {

    public static void main(String[] args) {
        test1();
        test2();
        System.out.println();
    }

    /**
     * ComparableUser实现java.lang.Comparable接口，可以不用指定比较器
     */
    private static void test2() {
        PriorityQueue<ComparableUser> priorityQueue = new PriorityQueue();
        priorityQueue.offer(new ComparableUser(3, "王五"));
        priorityQueue.offer(new ComparableUser(1, "张三"));
        priorityQueue.offer(new ComparableUser(2, "李四"));

        ComparableUser comparableUser;
        while ((comparableUser = priorityQueue.poll()) != null) {
            System.out.println(comparableUser);
        }
    }

    /**
     * User没有实现java.lang.Comparable接口，必须手动指定比较器，
     * 否则抛出异常Exception in thread "main" java.lang.ClassCastException: com.wang.common.domain.User cannot be cast to java.lang.Comparable
     */
    private static void test1() {
        PriorityQueue<User> priorityQueue = new PriorityQueue((a, b) -> {
            User user1 = (User) a;
            User user2 = (User) b;
            return user1.getId() - user2.getId();
        });
        priorityQueue.offer(new User(3, "王五"));
        priorityQueue.offer(new User(1, "张三"));
        priorityQueue.offer(new User(2, "李四"));
        User user;
        while ((user = priorityQueue.poll()) != null) {
            System.out.println(user);
        }
    }
}
